package com.self.cloudmall.oms.mq;


import com.rabbitmq.client.Channel;
import com.self.cloudmall.common.dto.OrderDto;
import com.self.cloudmall.oms.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@RabbitListener(queues = "order.release.queue")
@Component
public class OrderCloseMqHandler {

    @Autowired
    private OrderService orderService;

    /**
     * 消息延长30分钟，订单状态改为"已取消"，同时也要发消息解解锁库存
     */
    @RabbitHandler
    public void orderClose(OrderDto order, Message message, Channel channel){
         log.info("订单过期关闭的订单号：{}",order.getOrderSn());
        try {
            orderService.orderClose(order);
            //这里加手工调用支付宝收单接口，保证订单关闭，不能再支付
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            log.error("订单关闭异常：{}",e);
            try {
                //拒绝签收消息，重新放入队列中
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (Exception ex) {
                log.error("订单关闭异常-拒绝解锁异常：{}",ex);
            }
        }
    }
}
